<template>
<div id="box">
  <!--面包屑区域-->
  <el-breadcrumb>
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>商品管理</el-breadcrumb-item>
  <el-breadcrumb-item>分类参数</el-breadcrumb-item>
</el-breadcrumb>
<!--卡片区域-->
<el-card>
   <!--警告-->
   <el-alert
    title="注意：只允许为第三级分类设置相关参数！"
    type="warning" :closable="false" show-icon>
  </el-alert>
  <!--选择商品分类-->
  <el-row class="cat_opt">
    <el-col>
        <span>选择商品分类：</span>
        <el-cascader
    v-model="selectKeys"
    :options="catelist"
    :props="{ expandTrigger: 'hover', label: 'cat_name', value: 'cat_id', children: 'children' }"
    @change="handleChange"></el-cascader>
    </el-col>
  </el-row>
<!--页签区域-->
<el-tabs v-model="activeName" @tab-click="handleClick">
    <el-tab-pane label="动态参数" name="many">
        <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addshowVisible()">添加参数</el-button>
        <el-table
      :data="manyTableDate"
      border stripe>
      <el-table-column type="expand">
        <template v-slot="scope">
         <el-tag  closable v-for="(item, index) in scope.row.attr_vals" :key="index" @close="hanClose(index, scope.row)">{{ item }}</el-tag>
         <el-input
  class="input-new-tag"
  v-if="scope.row.inputVisible"
  v-model="scope.row.inputValue"
  ref="saveTagInput"
  size="small"
  @keyup.enter.native="handleInputConfirm(scope.row)"
  @blur="handleInputConfirm(scope.row)"
>
</el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
        </template>
      </el-table-column>
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column prop="attr_name" label="参数名称"></el-table-column>
      <el-table-column  label="操作">
        <template v-slot="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editshowVisible(scope.row.attr_id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row.attr_id)">删除</el-button>
            </template>
      </el-table-column>
      </el-table>
    </el-tab-pane>
    <el-tab-pane label="静态属性" name="only">
        <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addshowVisible()">添加属性</el-button>
        <el-table
      :data="onlyTableDate"
      border stripe>
      <el-table-column type="expand">
     <template v-slot="scope">
        <el-tag closable v-for="(item, index) in scope.row.attr_vals" :key="index" @close="hanClose(index, scope.row)">{{ item }}</el-tag>
        <el-input
  class="input-new-tag"
  v-if="scope.row.inputVisible"
  v-model="scope.row.inputValue"
  ref="saveTagInput"
  size="small"
  @keyup.enter.native="handleInputConfirm(scope.row)"
  @blur="handleInputConfirm(scope.row)"
>
</el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
    </template>
        
      </el-table-column>
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column prop="attr_name" label="属性名称"></el-table-column>
      <el-table-column  label="操作">
        <template v-slot="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editshowVisible(scope.row.attr_id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row.attr_id)">删除</el-button>
            </template>
      </el-table-column>
      </el-table>
    </el-tab-pane>
  </el-tabs>
</el-card>
<!--添加对话框-->
<el-dialog
  :title="titleType"
  :visible.sync="addVisible"
  width="50%" @close="closeadd">
  <el-form :model="addruleForm" :rules="addrules" ref="addruleForm" label-width="100px">
  <el-form-item :label="formName" prop="attr_name">
    <el-input v-model="addruleForm.attr_name"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParams">确 定</el-button>
  </span>
</el-dialog>
<!--修改对话框-->
<el-dialog
  :title="eidttitleType"
  :visible.sync="editVisible"
  width="50%" @close="closeedit">
  <el-form :model="editruleForm" :rules="addrules" ref="editruleForm" label-width="100px">
  <el-form-item :label="formName" prop="attr_name">
    <el-input v-model="editruleForm.attr_name"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editVisible = false">取 消</el-button>
    <el-button type="primary" @click="editParams">确 定</el-button>
  </span>
</el-dialog>
</div>
</template>

<script>
import { async } from 'rxjs'

export default {
    data() {
        return {
            //商品分类列表数据
            catelist: [],
            //选中的id
            selectKeys: [],
            //被激活的页签名称
            activeName: 'many',
            //动态数据
            manyTableDate: [],
            //静态数据
            onlyTableDate: [],
            //对话框的显示与隐藏
            addVisible: false,
            editVisible: false,
            //添加表单数据
            addruleForm: {
                attr_name: ''
            },
            //验证
            addrules: {
                attr_name: [{ required: true, message: '请输入对应名称', trigger: 'blur' }]
            },
            //id查的数据
            editruleForm: {},
            //input与input的切换
            inputVisible: false,
            //input输入的值
            inputValue: ''
        }
    },
    created() {
        this.getCateList()
    },
    computed: {
        isBtnDisabled() {
            //true为禁用
            if (this.selectKeys.length !== 3) return true
            return false
        },
        //选中的三级分类id
        cateID() {
            if (this.selectKeys.length !== 3) return null
            return this.selectKeys[this.selectKeys.length - 1]
        },
        //添加动态对话框标题
        titleType() {
            if (this.activeName === "many") {
                return '添加动态参数'
            } else {
                return "添加静态属性"
            }
        },
        //添加表单名字
        formName() {
            if (this.activeName === "many") {
                return "添加参数"
            }
            return "添加属性"
        },
        //修改动态对话框标题
        eidttitleType() {
            if (this.activeName === "many") {
                return '编辑动态参数'
            } else {
                return "编辑静态属性"
            }
        }
    },
    methods: {
        //获取商品分类的所有数据
        async getCateList() {
            let { data } = await this.$http.get("categories")
            // console.log(data)
            if (data.meta.status !== 200) return this.$message.error("获取商品分类数据失败")
            this.catelist = data.data
        },
        //多级选择改变
        async handleChange() {
            // console.log(this.selectKeys)\
            if (this.selectKeys.length !== 3) {
                this.selectKeys = []
                this.manyTableDate = []
                this.onlyTableDate = []
                return
            }
            this.getParamsList()
        },
        //获取参数列表数据
        async getParamsList() {
            let { data } = await this.$http.get(`categories/${this.cateID}/attributes`, { params: { sel: this.activeName } })

            if (data.meta.status !== 200) return this.$message.error("获取参数列表失败")
            data.data.forEach((item) => {
                item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
                //input与input的切换
                item.inputVisible = false
                //input输入的值
                item.inputValue = ''
            })
            console.log(data)
            if (this.activeName === 'many') {
                this.manyTableDate = data.data
            } else {
                this.onlyTableDate = data.data
            }
        },

        //页签的点击事件
        handleClick() {
            this.getParamsList()
        },
        //点击添加
        addshowVisible() {
            this.addVisible = true
        },
        //关闭对话框
        closeadd() {
            this.$refs.addruleForm.resetFields()
        },
        //点击确定进行添加
        addParams() {
            this.$refs.addruleForm.validate(async (bool) => {
                if (!bool) return
                let { data } = await this.$http.post(`categories/${this.cateID}/attributes`, { attr_name: this.addruleForm.attr_name, attr_sel: this.activeName })
                // console.log(data)
                if (data.meta.status !== 201) return this.$message.error("添加动态参数失败")
                this.$message.success("添加动态参数成功")
                this.getParamsList()
                this.addVisible = false
            })
        },
        //点击编辑
        async editshowVisible(id) {
            // console.log(id)
            let { data } = await this.$http.get(`categories/${this.cateID}/attributes/${id}`, { params: { attr_sel: this.activeName } })
            // console.log(data)
            if (data.meta.status !== 200) return this.$message.error("id数据获取失败")
            this.editruleForm = data.data
            this.editVisible = true
        },
        //关闭对话框
        closeedit() {
            this.$refs.editruleForm.resetFields()
        },
        //点击确定，进行编辑
        editParams() {
            this.$refs.editruleForm.validate(async (bool) => {
                if (!bool) return
                let { data } = await this.$http.put(`categories/${this.cateID}/attributes/${this.editruleForm.attr_id}`, { attr_name: this.editruleForm.attr_name, attr_sel: this.activeName })
                // console.log(data)
                if (data.meta.status !== 200) return this.$message.error("参数编辑失败")
                this.$message.success("参数编辑成功")
                this.getParamsList()
                this.editVisible = false
            })
        },
        //点击删除，进行删除
        async deleteParams(id) {
            let h = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if (h !== 'confirm') return this.$message.info("已取消删除")
            let { data } = await this.$http.delete(`categories/${this.cateID}/attributes/${id}`)
            // console.log(data)
            if (data.meta.status !== 200) return this.$message.error("参数删除失败")
            this.$message.success("删除成功")
            this.getParamsList()
        },
        //失去焦点和enter
        async handleInputConfirm(row) {
            if (row.inputValue.trim().length === 0) {
                row.inputValue = ''
                row.inputVisible = false
                return
            }
            row.attr_vals.push(row.inputValue.trim())
            row.inputValue = ""
            row.inputVisible = false
            //编辑参数
            let { data } = await this.$http.put(`categories/${this.cateID}/attributes/${row.attr_id}`, { attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(",") })
            if (data.meta.status !== 200) return this.$message.error("参数编辑失败")
            this.$message.success("参数编辑成功")
        },
        //点击new tag
        showInput(row) {
            row.inputVisible = true
            //让文本框自动获得焦点
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        //删除
        async hanClose(i, row) {
            let h = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if (h !== "confirm") return this.$message.info("已取消删除")
            row.attr_vals.splice(i, 1)
            let { data } = await this.$http.put(`categories/${this.cateID}/attributes/${row.attr_id}`, { attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(",") })
            if (data.meta.status !== 200) return this.$message.error("参数删除失败")
            this.$message.success("参数删除成功")
        }
    }
}
</script>

<style lang="less" scoped>
.cat_opt {
    margin: 15px 0
}

.el-tag {
    margin: 10px
}

.input-new-tag {
    width: 120px
}
</style>